/*
https://leetcode-cn.com/problems/couples-holding-hands/solution/qing-lu-qian-shou-by-leetcode-gl1c/
 */
public class Solution765 {

    int[] b;

    public int minSwapsCouples(int[] row) {
        b=new int[row.length/2];
        for (int i=0;i<b.length;i++){
            b[i]=i;
        }
        for (int i=0;i<row.length;i+=2){
            b[find(row[i]/2)]=b[find(row[i+1]/2)];
        }
        int count=0;
        for (int i=0;i<b.length;i++){
            if (find(i)==i){
                count++;
            }
        }
        return b.length-count;
    }

    private int find(int i) {
        while (b[i]!=i){
            i=b[i];
        }
        return i;
    }

    public static void main(String[] args) {
        System.out.println(new Solution765().minSwapsCouples(new int[]{0,2,1,3}));
    }
}
